#API functions
from django.http import HttpResponse
from .models import *
from forum.forms import *
from .utilities import page_guide, get_permissions, has_permission
from django.shortcuts import render_to_response, redirect
from django.contrib.auth import authenticate, login, logout
import json, re

#updated by author @ 2014/5/30
def user(request, action):
    if action == 'login':
        user_auth = authenticate(
                username=request.POST['username'],
                password=request.POST['password']
                )

        if user_auth is not None:
            if user_auth.is_active:
                login(request, user_auth)
                return page_guide(request, to='referer')
            else:
                #need a better error page
                return HttpResponse(status=401)
        else:
            #need a better error page
            return HttpResponse(status=404)

    elif action == 'ajaxlogin':
        if user(request, 'auth'):
            return HttpResponse("0")
        else:
            return HttpResponse("1")

    elif action == 'auth':
        user_auth = authenticate(
                username=request.POST['username'],
                password=request.POST['password']
                )

        if user_auth is not None:
            login(request, user_auth)
            return True
        else:
            return False

    elif action == 'logout':
        logout(request)
        return page_guide(request, to='referer')

    elif action == 'add':
        form = UserForm(request.POST)
        if form.is_valid():
            try:
                ForumUser.objects.create_user(
                        username = form.cleaned_data['username'],
                        password = form.cleaned_data['password'],
                        email = form.cleaned_data['email']
                        )
            except Exception, e:
                return HttpResponse("1")
            else:
                return HttpResponse("0")
        else:
            return HttpResponse("2")

    elif action == 'register':
        if not request.POST['password'] == request.POST['password_again']:
            #need a better error page
            return HttpResponse(status=400)

        try:
            #need better logic
            ForumUser.objects.create_user(
                    username = request.POST['username'],
                    password = request.POST['password'],
                    email = request.POST['email']
                    )
        except:
            #need a better error page
            return HttpResponse("err2")
        else:
            new_user = authenticate(
                    username = request.POST['username'],
                    password = request.POST['password']
                    )
            login(request, new_user)
            return page_guide(request, to='referer')

    elif action == 'update':
        pass

    elif action == 'del':
        if user(request, 'auth'):
            try:
                for item_id in request.POST.getlist(u'selected_items[]'):
                    item_id = int(item_id)
                    user_dying = ForumUser.objects.get(id=item_id)
                    if int(request.POST['delete_relate']) == 1:
                        Topic.objects.filter(author__id=user_dying.id).delete()
                        Push.objects.filter(author__id=user_dying.id).delete()
                    user_dying.delete()
            except:
                return HttpResponse('1')
            else:
                return HttpResponse('0')
        else:
            return HttpResponse('2')

    elif action == 'ban':
        FroumUser.objects.filter(id=id).update(is_active=False)
        return page_guide(request)

#updated by author @ 2014/5/31
def board(request, action, id=0):
    if action == 'add':
        category = BoardCategory.objects.get(pk=int(request.POST['category']))
        board_base = Board(category=category)

        form = BoardForm(request.POST, instance=board_base)
        if form.is_valid():
            try:
                form.save()
            except:
                #need a better error page
                return HttpResponse(status=400)
            else:
                return page_guide(request, to='referer')

    elif action == 'update':
        try:
            board_base = Board.objects.get(pk=id)
        except:
            return HttpResponse("1")

        form = BoardUpdateForm(request.POST, instance=board_base)
        if form.is_valid():
            try:
                form.save()
            except:
                return HttpResponse("1")
            else:
                return HttpResponse("0")
        else:
            return HttpResponse(json.dumps(form.errors))

    elif action == 'del':
        try:
            Board.objects.filter(id=id).delete()
        except:
            #need a better error page
            return HttpResponse(status=500)
        else:
            return page_guide(request, to='referer')

#created by author @ 2014/5/31
def board_category(request, action, id=0):
    if action == 'add':
        form = BoardCategoryForm(request.POST)
        try:
            form.save()
        except:
            result = ''
            for k, v in form.errors.iteritems():
                result = result + str(k) + ': ' + str(v) + '</ br>'
            return HttpResponse(result)
            #need a better error page
        else:
            return page_guide(request, to='referer')

    elif action == 'update':
        category_base = BoardCategory.objects.get(pk=id)

        form = BoardCategoryForm(request.POST, instance=board_base)
        if form.is_valid():
            try:
                form.save()
            except:
                #need a better error page
                return HttpResponse(status=400)
            else:
                return page_guide(request, to='referer')

    elif action == 'del':
        try:
            BoardCategory.objects.filter(id=id).delete()
        except:
            #need a better error page
            return HttpResponse(status=500)
        else:
            return page_guide(request, to='referer')

#updated by author @ 2014/5/31
def topic(request, action, board='', id=0):
    if action == "add":
        if request.user.is_anonymous():
            author = None
        else:
            author = request.user

        post_base = Topic(
                post_ip=request.META['REMOTE_ADDR'],
                board=board,
                author=author
                )

        form = TopicForm(request.POST, instance=post_base)
        if form.is_valid():
            try:
                new_topic = form.save()

                if re.match(r'\d+(,\d+)*', request.POST['uploaded_attachments']):
                    ids = re.split(r',', request.POST['uploaded_attachments'])
                    attachments = Attachment.objects.in_bulk(ids).values()
                    new_topic.attachments.add(*attachments)

                new_topic.save()
            except Exception, e:
                return HttpResponse('2')
            else:
                return redirect('board', tboard=board.name)
        else:
            for k, v in form.errors:
                result = result + k + ' ' + v + '<br />'
            return HttpResponse(result)

    elif action == "del":
        topic = Topic.objects.get(pk=id)
        board_name = topic.board.name
        topic.delete()
        return redirect('board', tboard=board_name)

    elif action == "edit":
        try:
            post = Topic.objects.get(pk=id)
        except:
            #need a better error page
            return HttpResponse(status=400)

        post.title = request.POST['title']
        post.content = request.POST['content']
        post.save()

        return redirect('topic', id=post.tree_node)

    elif action == "reply":
        try:
            father_post = Topic.objects.get(pk=id)
        except:
            #need a better error page
            return HttpResponse(status=400)

        if has_permission(request, father_post, 'reply'):
            if request.user.is_anonymous():
                author = None
            else:
                author = request.user
        else:
            return HttpResponse("You need permission to do this.")

        post_base = Topic(
                post_ip=request.META['REMOTE_ADDR'],
                father_node=father_post,
                tree_node=father_post.tree_node,
                board=father_post.board,
                author = author
                )
        form = TopicForm(request.POST, instance=post_base)
        if form.is_valid():
            try:
                form.save()
            except:
                #need a better error page
                return HttpResponse(status=400)
            else:
                return redirect('board', tboard=father_post.board.name)
        else:
            #need a better error page
            return HttpResponse(status=400)

#updated by author @ 2014/5/31
def push(request, action, id):
    if action == 'add':
        try:
            father_post = Topic.objects.get(pk=id)
        except:
            return HttpResponse("1")

        if not has_permission(request, father_post, 'push'):
            return False

        if request.user.is_anonymous():
            author = None
        else:
            author = request.user

        push_base = Push(post_ip=request.META['REMOTE_ADDR'], author = author, father_node=father_post, attitude=None)

        form = PushForm(request.POST, instance=push_base)
        if form.is_valid():
            try:
                form.save()
            except:
                return False
            else:
                return True
        else:
            return False

    elif action == 'del':
        try:
            Push.objects.get(pk=id).delete()
            return page_guide(request, to='referer')
        except:
            #need a better error page
            return HttpResponse("err")

#created by author @ 2014/6/11
def message(request, action, id):
    if not request.user.is_superuser:
        return HttpResponse("You don't have permission to manage messages.")

    if action == 'create':
        form = MessageForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except:
                return HttpResponse("Error occured when trying to save message.")
            else:
                return page_guide(request, to='referer')
        else:
            return HttpResponse("Error when validating message input.")
    elif action == 'update':
        try:
            message = Message.objects.get(pk=id)
        except Message.DoesNotExist:
            return HttpResponse("Error occured when saving changes.")

        message.name = request.POST['name']
        message.content = request.POST['content']
        message.save()

        return redirect("manage", part="message")
    elif action == 'del':
        if user(request, 'auth'):
            try:
                Message.objects.get(pk=id).delete()
            except:
                return HttpResponse(2)
            else:
                return HttpResponse(0)
        else:
            return HttpResponse(1)
